【发布时间】:2020-09-13 23:05:54
【问题描述】:
我找到this site 并运行代码。 该示例代码运行良好。 这段代码在这里。
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_State createState() => _State();
}
class _State extends State<MyApp> {
bool isSwitched = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter - tutorialkart.com'),
),
body: Center(
child: Switch(
value: isSwitched,
onChanged: (value) {
setState(() {
isSwitched = value;
print(isSwitched);
});
},
activeTrackColor: Colors.lightGreenAccent,
activeColor: Colors.green,
),
)
);
}
}
固定 Switch Widget 放置在 ShowDialog 内。
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_State createState() => _State();
}
class _State extends State<MyApp> {
bool isSwitched = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(onPressed: () {
var ret = showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Container(
height: MediaQuery.of(context).size.height / 3,
child: Center(
child: Switch(
value: isSwitched,
onChanged: (value) {
setState(() {
isSwitched = value;
print(isSwitched);
});
},
activeTrackColor: Colors.lightGreenAccent,
activeColor: Colors.green,
),
),
),
);
},
);
},child: Text("show toggle button"),),
),
);
}
}
isSwitched 变量没有改变。
如果单独运行 Switch Widget,它可以正常工作。
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_State createState() => _State();
}
class _State extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Container(
height: MediaQuery.of(context).size.height / 3,
child: Center(
child: SwitchWidget(),
),
),
);
},
);
},child: Text("show toggle button"),),
),
);
}
}
class SwitchWidget extends StatefulWidget {
@override
_SwitchWidgetState createState() => _SwitchWidgetState();
}
class _SwitchWidgetState extends State<SwitchWidget> {
bool isSwitched = false;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.transparent,
body: Center(
child: Switch(
value: isSwitched,
onChanged: (value) {
setState(() {
isSwitched = value;
print(isSwitched);
});
},
activeTrackColor: Colors.lightGreenAccent,
activeColor: Colors.green,
),
)
);
}
}
有没有办法将 Switch Widget 放入 ShowDialog 而不将其分离到另一个有状态的小部件中?
【问题讨论】:
标签: flutter showdialog