Flutter StatelessWidget、StatefulWidget的简单使用

StatelessWidget

定义MyTestView的StatelessWidget
声明title,在使用MyTestView时传入title值

class MyTestView extends StatelessWidget {
  final String title;
  MyTestView({Key key, this.title}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(title),
    );
  }
}

使用

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'my app',
      home: Scaffold(
        appBar: AppBar(
          title: Text('首页'),
        ),
        body: MyTestView(
          title: '文本',
        ),
      ),
    );
  }
}
image.png

StatefulWidget

定义MyTestView的StatefulWidget
声明callBack的点击回调,在使用MyTestView时可接收点击结果回调。

class MyTestView extends StatefulWidget {
  final void Function(int index) callBack;
  MyTestView({Key key, this.callBack}) : super(key: key);
  @override
  _MyTestViewState createState() => _MyTestViewState();
}

class _MyTestViewState extends State {
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Column(
        children: [
          Container(
            color: Colors.yellow,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
            child: Text('$_index'),
          ),
          GestureDetector(
            onTap: work,
            child: Container(
              color: Colors.blue,
              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
              child: Text('点击'),
            ),
          ),
        ],
      ),
    );
  }

  int _index = 0;
  void work() {
    setState(() {
      _index++;
      if (widget.callBack != null) {
        widget.callBack(_index);
      }
    });
  }
}

使用

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'my app',
      home: Scaffold(
        appBar: AppBar(
          title: Text('首页'),
        ),
        body: MyTestView(
          callBack: (index) {
            print('$index');
          },
        ),
      ),
    );
  }
}

image.png

image.png

StatefulWidget的核心是setState方法,可以变更当前widget的页面内容。

setState(() {
  /// 页面数据变更,引起页面内容变化
});

你可能感兴趣的:(Flutter StatelessWidget、StatefulWidget的简单使用)