Main.dart:
import 'package:flutter/material.dart';
import 'package:mypackage/widgets/home_widget.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "My App",
theme: ThemeData(primarySwatch: Colors.blueGrey),
home: Home(),
);
}
}
Home.dart:
import 'package:flutter/material.dart';
import 'package:mypackage/widgets/secondary_page.dart';
import 'package:mypackage/widgets/home_view.dart';
import 'package:mypackage/widgets/settings_page.dart';
class Home extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _HomeState();
}
}
class _HomeState extends State<Home> {
int currentPageIndex = 0;
final List<Widget> pageWidgets = [HomeView(), SecondaryPage(), SettingsPage()];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("My App"),
centerTitle: true,
),
body: pageWidgets[currentPageIndex],
bottomNavigationBar: BottomNavigationBar(
onTap: onTabTapped,
currentIndex: currentPageIndex,
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home), label: "Tab One"),
BottomNavigationBarItem(
icon: new Icon(Icons.account_balance), label: "Tab Two"),
BottomNavigationBarItem(
icon: new Icon(Icons.settings), label: "Tab Three"),
],
),
floatingActionButton: FloatingActionButton(onPressed: () {
// Update data from here
HomeView().updateDisplay();
}));
}
// Changes the index when the tapped page has loaded
void onTabTapped(int index) {
setState(() {
currentPageIndex = index;
});
}
}
HomeView.dart:
import 'package:flutter/material.dart';
import 'package:mypackage/models/mydisplay.dart';
import 'package:mypackage/network/mydata.dart';
class HomeView extends StatelessWidget {
final List<MyDisplay> dataList = [
new MyDisplay("Sample Display",
"SampleFile", 0),
];
Future<void> updateDisplay() async {
MyData myData = new MyData();
dataList.forEach((d) async {
d.changePercentage = await myData
.getDataPercentage("assets/data/" + d.fileName + ".xml");
print(d.dataName +
" change percentage: " +
d.changePercentage.toString() +
"%");
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: new ListView.builder(
itemCount: dataList.length,
itemBuilder: (BuildContext context, int index) =>
buildCard(context, index)),
);
}
Widget buildCard(BuildContext context, int index) {
return Container(
child: Card(
color: Colors.teal.shade200,
child: Padding(
padding: const EdgeInsets.all(25),
child: Column(children: <Widget>[
Text(dataList[index].dataName,
style: new TextStyle(
fontSize: 20, fontWeight: FontWeight.bold)),
Text(dataList[index].changePercentage.toString() + "%")
]))));
}
}
当我从floatingActionButton调用updateDisplay()方法时,它按预期工作,数据被打印到控制台,但似乎没有更新实际的UI,卡片的内容仍然保持在它们最初的设置值。
澄清一下:如何从有状态的小部件中更新列表视图内(在无状态小部件内)卡片的内容?
如果这是重复问题,我很抱歉,我已经寻找答案并继续寻找,但我只是无法让它工作。