【发布时间】:2019-11-11 10:59:11
【问题描述】:
我正在 Flutter 中构建一个 To App,我想通过使用复选框来更改我的个人 todo 的布尔值。虽然值确实发生了变化,但它不会反映在 UI 中。我是不是做错了什么?
一开始,我没有使用布尔值来更改我的 Todo 的已完成属性的值。我试图用复选框更改它,但它似乎不起作用,这就是为什么我放了一个布尔值。
import 'package:flutter/material.dart'; 导入'./todo.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'To do app',
theme: ThemeData(
brightness: Brightness.light,
primarySwatch: Colors.green,
),
darkTheme: ThemeData(
brightness: Brightness.light,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final List _myTodos = [
Todo(title: 'Take the dogs for a walk', completed: false, id: '1'),
Todo(title: 'Go out for a run', completed: true, id: '2')
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('To do app'),
centerTitle: true,
),
body: _myTodos.isEmpty
? Text(
'Press the button to add a new Todo',
style: TextStyle(fontSize: 20),
)
: Column(
children: _myTodos.map((todo) {
bool completed = todo.completed;
return Row(
children: <Widget>[
Checkbox(
value: completed,
onChanged: (bool newValue) {
print(completed);
setState(() {
completed = newValue;
print(completed);
});
},
),
Text(
todo.title,
style: TextStyle(fontSize: 16),
)
],
);
}).toList()),
floatingActionButton: FloatingActionButton(
onPressed: () {},
elevation: 8,
child: Icon(Icons.add),
),
);
}
}
【问题讨论】:
-
你为什么要把它分配给一个新的 bool ?
bool completed = todo.completed;尝试不分配它,只需使用value: todo.completed,和todo.completed =newValue; -
感谢您的评论。这就是我一开始所做的,但我收到了这个错误消息
Class 'Todo' has no instance setter 'completed='. Receiver: Instance of 'Todo' Tried calling: completed=true -
也可以使用
CheckboxListTile,例如:children: _myTodos.map((todo) => CheckboxListTile( controlAffinity: ListTileControlAffinity.leading, title: Text( todo.title, style: TextStyle(fontSize: 16), ), value: todo.completed, onChanged: (bool newValue) => setState(() => todo.completed = newValue), ) ).toList() -
谢谢,我已经重构了我的代码:)
-
当然,欢迎您
标签: flutter