flutter从极简一步步增加 - 图2

极简起步

  1. import 'package:flutter/material.dart';
  2. void main() {
  3. runApp(Text("hello world",
  4. textAlign: TextAlign.center,));
  5. //textAlign: TextAlign.center是不能少的,少了会报错
  6. }

提取组件

  1. import 'package:flutter/material.dart';
  2. void main() {
  3. runApp(MyApp());
  4. //textAlign: TextAlign.center是不能少的,少了会报错
  5. }
  6. //分离出MyApp
  7. class MyApp extends StatelessWidget {
  8. @override
  9. Widget build(BuildContext context) {
  10. return Text(
  11. "hello6",
  12. textAlign: TextAlign.center,);
  13. }
  14. }

分离文件

提取出myApp.dart

  1. import 'package:flutter/material.dart';
  2. class MyApp extends StatelessWidget {
  3. @override
  4. Widget build(BuildContext context) {
  5. return Text(
  6. "hello6",
  7. textAlign: TextAlign.center,);
  8. }
  9. }

main.dart文件内容

  1. import 'package:flutter/material.dart';
  2. import 'package:myapp/myApp.dart';
  3. void main() {
  4. runApp(MyApp());
  5. }

引入Center

myApp.dart文件内容

  1. import 'package:flutter/material.dart';
  2. class MyApp extends StatelessWidget {
  3. @override
  4. Widget build(BuildContext context) {
  5. return Center(
  6. child: Text(
  7. "hello",
  8. textAlign: TextAlign.center,
  9. textDirection: TextDirection.rtl,
  10. ),
  11. );
  12. }
  13. }

引入scaffold

引入scaffold同时必须引入MaterialApp,否则会报错

  1. import 'package:flutter/material.dart';
  2. class MyApp extends StatelessWidget {
  3. @override
  4. Widget build(BuildContext context) {
  5. return MaterialApp(
  6. home: Scaffold(
  7. body: Center(
  8. child: Text(
  9. "hello",
  10. textAlign: TextAlign.center,
  11. textDirection: TextDirection.rtl,
  12. ),
  13. )));
  14. }
  15. }

操作中存在的问题

编写极简示例的过程中,一些代码变化不能成功热更新,这个时候可以重新启动
修改主文件以外的文件造成的代码变化,不能触发热更新,需要ctr+F5,引发热更新,如果热更新不能体现代码变化,尝试重新启动