将项目添加到列表时如何刷新我的 ListView.builder?
ListView.builder(
itemCount: propList.length,
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemBuilder: (context,index)=> Text(propList[index]),
)
我的按钮是
FlatButton(onPressed: (){propList.add('text');}, child: Text('add'))
最佳答案
假设您已经扩展了 StatefulWidget
,则每次更改状态时都必须调用 setState
。前任:
setState(() { propList.add('text'); });
这是一个快速示例:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) => MaterialApp(home: MyList());
}
class MyList extends StatefulWidget {
@override
_MyListState createState() => _MyListState();
}
class _MyListState extends State<MyList> {
List<String> propList = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My List'),
),
body: ListView.builder(
itemCount: propList.length,
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemBuilder: (context,index)=> Text(propList[index]),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => propList.add('text')),
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
关于list - 如何刷新 ListView.builder flutter ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59927528/