Flutter 官方案例代码

import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
import 'package:provider/provider.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    ///Provider 获取数据状态的前提是在顶层套上ChangeNotifierProvider():
    return ChangeNotifierProvider(
      create: (context) => MyAppState(),
      child: MaterialApp(
        title: 'Namer App',
        theme: ThemeData(
          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
          useMaterial3: true,
        ),
        home: MyHomePage(),
      ),
    );
  }
}

///共享数据类,继承 `ChangeNotifier`
///Provider 获取数据状态有两种方式:
///
/// 使用 Provider.of(context) 获取 DataInfo
/// 使用 Consumer
/// 不过这两种方式都需要在顶层套上ChangeNotifierProvider():
class MyAppState extends ChangeNotifier{
  var current = WordPair.random();

  void getNext(){
    current = WordPair.random();
    ///使用 notifyListeners() 函数通知监听者以更新界面
    notifyListeners();
  }

  var favorites = <WordPair>{}; /// {} 为Set类型, [] 为 List类型

  void toggleFavorite(){
    favorites.contains(current) ? favorites.remove(current) : favorites.add(current);
    ///使用 notifyListeners() 函数通知监听者以更新界面
    notifyListeners();
  }

  void removeFacorite(WordPair pair){
    if(favorites.contains(pair)) favorites.remove(pair);
    notifyListeners();
  }

}

class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var selectedIndex = 0;
  @override
  Widget build(BuildContext context) {
    Widget page;
    switch(selectedIndex){
      case 0 :
        page = GeneratorPage();
        break;
      case 1:
        page = FavoritesPage();
        break;
      default:
        throw UnimplementedError("no widget for $selectedIndex");
    }

    return LayoutBuilder(builder: (context,constraints) {
        return Scaffold(
          body: Row(
            children: [
              SafeArea(
                child: NavigationRail(
                  extended: constraints.maxWidth >= 600,
                  destinations: [
                    NavigationRailDestination(
                      icon: Icon(Icons.home),
                      label: Text('Home'),
                    ),
                    NavigationRailDestination(
                      icon: Icon(Icons.favorite),
                      label: Text('Favorites'),
                    ),
                  ],
                  selectedIndex: selectedIndex,
                  onDestinationSelected: (value) {
                    setState(() {
                      selectedIndex = value;
                    });
                    print('selected: $value');
                  },
                ),
              ),
              Expanded(
                child: Container(
                  color: Theme.of(context).colorScheme.primaryContainer,
                  child: page,
                ),
              ),
            ],
          ),
        );
      }
    );
  }
}

class FavoritesPage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    /// 获取状态的几种方式
    ///var appState = Provider.of<MyAppState>(context);
    var appState = context.watch<MyAppState>();
    var favorites = appState.favorites;
    var theme = Theme.of(context);

    if(favorites.isEmpty){
      return Center(
        child: Text('No favorites yes.'),
      );
    }

    return ListView(
      children: [
        Padding(
            padding: const EdgeInsets.all(20),
          child: Text('You hava '
              '${favorites.length} favorites: '),
        ),
        for (var value in favorites)
          ListTile(
            leading: IconButton(
              icon: Icon(Icons.delete_outline,semanticLabel: 'Delete',),
              color: theme.colorScheme.primary,
              onPressed: (){
                appState.removeFacorite(value);
              },
            ),
            title: Text(
              value.asLowerCase,
              semanticsLabel: value.asPascalCase,
            ),
            // leading: Icon(Icons.favorite),
            // title: Text(value.asLowerCase),
          )
      ],
    );

  }
}

class GeneratorPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var appState = context.watch<MyAppState>();
    var pair = appState.current;

    IconData icon;
    if (appState.favorites.contains(pair)) {
      icon = Icons.favorite;
    } else {
      icon = Icons.favorite_border;
    }
    ///获取状态的方式
    // return Consumer<MyAppState>(
    //     builder: (context,myAppState,_) => Center(
    //       child: Column(
    //         mainAxisAlignment: MainAxisAlignment.center,
    //         children: [
    //           BigCard(pair: pair),
    //           SizedBox(height: 10),
    //           Row(
    //             mainAxisSize: MainAxisSize.min,
    //             children: [
    //               ElevatedButton.icon(
    //                 onPressed: () {
    //                   appState.toggleFavorite();
    //                 },
    //                 icon: Icon(icon),
    //                 label: Text('Like'),
    //               ),
    //               SizedBox(width: 10),
    //               ElevatedButton(
    //                 onPressed: () {
    //                   appState.getNext();
    //                 },
    //                 child: Text('Next'),
    //               ),
    //             ],
    //           ),
    //         ],
    //       ),
    //     )
    // );

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          BigCard(pair: pair),
          SizedBox(height: 10),
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              ElevatedButton.icon(
                onPressed: () {
                  appState.toggleFavorite();
                },
                icon: Icon(icon),
                label: Text('Like'),
              ),
              SizedBox(width: 10),
              ElevatedButton(
                onPressed: () {
                  appState.getNext();
                },
                child: Text('Next'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}


class BigCard extends StatelessWidget{

  const BigCard({
    super.key,
    required this.pair,
  });

  final WordPair pair;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);  //获取应用的当前主题
    final style = theme.textTheme.displayMedium!.copyWith(
      color: theme.colorScheme.onPrimary,
    );
    return Card(
      color: theme.colorScheme.primary, //定义为与主题相同的颜色
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Text(
          pair.asLowerCase,
          style: style,
          semanticsLabel: "${pair.first} ${pair.second}",
        ),
      ),
    );
  }
}

posted @ 2023-07-06 10:45  SpringCore  阅读(204)  评论(0编辑  收藏  举报