我很难理解
Widget BuildContext
以及
Builder BuildContext
从以下代码段开始:
@override
Widget build(BuildContext context) {
和
new Builder(
builder: (BuildContext context){
通过使用
小部件BuildContext
snackbar不会出现在ui中,但在日志中会显示一个错误,表明
Scaffold.of() Context
使用时没有脚手架
Builder context
一切正常。
Scaffold.of(context).showSnackBar(
new SnackBar(content: new Text('Processing Data')));
编辑:main.dart文件:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'APP'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final formKey = new GlobalKey<FormState>();
String username;
@override
//This context
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
body: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
new Flexible(
child: new Container(
child: new Center(
child: new Text(widget.title),
),
),
flex: 1,
),
new Form(
key: formKey,
child:
new Row(children: <Widget>[
new Flexible(child:
new Container(
margin: EdgeInsets.zero,
child: new TextFormField(
decoration:
new InputDecoration(
hintText: 'Username',
labelText: "1",
labelStyle: new TextStyle(color: new Color.fromARGB(255, 0, 0, 0)),
),
validator: (val) => val.isEmpty? 'Username can\'t be empty.' : null,
),
),
flex: 1,
),
new Flexible(child:
new Container(
margin: EdgeInsets.only(
left: 8.0,
right: 8.0,
),
child: new TextFormField(
decoration: new InputDecoration(
border: InputBorder.none,
hintText: "Password",
),
validator: (val) => val.isEmpty? 'Password can\'t be empty.' : null,
obscureText: true,
),
),
flex: 1,
),
new Container(
child:
new Builder(
//And this context
builder: (BuildContext context){
return RaisedButton(
child: new Text("Sign in"),
onPressed: (){
if (formKey.currentState.validate()) {
// If the form is valid, display a snackbar. In the real world, you'd
// often want to call a server or save the information in a database
Scaffold.of(context).showSnackBar(
new SnackBar(content: new Text('Processing Data')));
}
},
);
},
),
),
],
),
),
],
),
),
);
}
}