Flutter之教你制作一个选择吃啥APP(三)

214 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

书接上文

我们已经实现了输入菜名和生成菜单这个过程了 接下来就开始听天由命了 让应用决定你吃啥东西了

其实这个过程也很简单 就是随机数 随机出来就行了

代码如下:

FlatButton(
    color: Colors.blue,
    textColor: Colors.white,
    onPressed: () {
      if (foodList.length == 0) {
        ToastHelper.error("不添加菜单吃啥子");
        return;
      } else if (foodList.length == 1) {
        ToastHelper.error("就一样菜你还选什么????");
        return;
      } else if (foodList.length == 30) {
        ToastHelper.error("三十样菜  你开饭店的吧!!!");
      }
      Random r = new Random();
      int randomNum = r.nextInt(foodList.length);
      ToastHelper.toast("我不要你觉得,我要我觉得你要吃" + foodList[randomNum].toString());
    },
    child: const Text('预料之外意想之中')),

首先我们需要一个按钮 搞一个点击事件 这里我们主要是获取我们上文的保存菜名的foodList 然后做一些小判断 判断很简单就不多做解释了 其中有个重点是用到了ToastHelper 和 Random

Toast我就不展开了 有兴趣的自己去查一下吧

Random主要是一个获取随机的一个类 我们通过这个类的nextInt()去获取了一个在菜单名list长度里的数字,int randomNum = r.nextInt(foodList.length);

然后通过这个随机数去弹出随机到的菜单里的菜名是啥子

不过注意的是 如果想要居中的话 需要设置

mainAxisAlignment: MainAxisAlignment.center,

最后完整代码如下: 其中main.dart为

import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:smwd/utils/to.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ToastHelper.init(MaterialApp(
      title: 'Choice',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Choice'),
    ));
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Widget> listTitle = [];
  List<String> foodList = [];
  /*灰色分割线*/
  var divider = Divider(
    color: Colors.grey,
  );
  bool delete = true;
  TextEditingController _textEditingController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //取消进页面软键盘自动弹起
    listTitle = [];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () {
          showDialog<Null>(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return AlertDialog(
                title: const Text('菜单选项'),
                content:
                StatefulBuilder(builder: (context, StateSetter setState) {
                  return Row(
                    children: [
                      Expanded(
                        child: TextField(
                          controller: _textEditingController,
                          autofocus: true,
                          onSubmitted: (value) async => {},
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                            contentPadding: EdgeInsets.symmetric(
                                horizontal: 15, vertical: 15),
                            labelText: '菜名',
                            floatingLabelBehavior: FloatingLabelBehavior.always,
                            hintText: '腐竹炒肉',
                          ),
                        ),
                      )
                    ],
                  );
                }),
                actions: <Widget>[
                  new FlatButton(
                    child: new Text('确定'),
                    onPressed: () {
                      Navigator.pop(context);
                      if (_textEditingController.text.trim() == "") {
                        ToastHelper.error("吃空气????");
                        return;
                      }
                      foodList.add(_textEditingController.text);
                      _textEditingController.text = "";
                    },
                  ),
                ],
              );
            },
          ).then((val) {
            setState(() {
              initData();
              listTitle.add(
                  Container(

                    height: 500,
                    child: ListView.builder(
                        itemCount: foodList.length,

                        itemBuilder: (BuildContext context, int poistion) {
                          return GestureDetector(
                              child: Container(
                               margin: EdgeInsets.all(4.0),
                                height: 50,
                                child: rich(poistion)
                              ),

                              //item 点击事件
                              onTap: () {
                                print("点击到第" + poistion.toString());
                                setState(() {
                                });
                              },
                              //item 长按事件
                              onLongPress: () {
                                setState(() {
                                  /**/
                                  showDialog<Null>(
                                      context: context,
                                      barrierDismissible: false,
                                      builder: (BuildContext context) {
                                        return AlertDialog(
                                          title: const Text('你确定删除这个菜单'),
                                          content:
                                          StatefulBuilder(builder: (context,
                                              StateSetter setState) {
                                            return Row(
                                              children: [
                                                Expanded(
                                                  child: Text(
                                                      "你确定?"
                                                  ),
                                                )
                                              ],
                                            );
                                          }),
                                          actions: <Widget>[
                                            FlatButton(
                                              child: new Text('确定'),
                                              onPressed: () {
                                                setState(() {
                                                  Navigator.pop(context);
                                                  setState(() {
                                                    foodList.removeAt(poistion);
                                                    initData();
                                                  });
                                                });
                                              },
                                            ),
                                          ],

                                        );
                                      });


                                  /* */
                                });
                                print("长按" + poistion.toString());
                              }
                          );
                        }),
                  )

              );
              glueDischargeFurnaceResult(listTitle);
            });
          });
        },
        label: const Text('添加菜单选项'),
      ),
      appBar: AppBar(
        actions: [
          IconButton(icon: Icon(Icons.cached), onPressed: () => initALLData()),
        ],
        title: Text(widget.title),
      ),
      body: GestureDetector(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              FlatButton(
                  color: Colors.blue,
                  textColor: Colors.white,
                  onPressed: () {
                    if (foodList.length == 0) {
                      ToastHelper.error("不添加菜单吃啥子");
                      return;
                    } else if (foodList.length == 1) {
                      ToastHelper.error("就一样菜你还选什么????");
                      return;
                    } else if (foodList.length == 30) {
                      ToastHelper.error("三十样菜  你开饭店的吧!!!");
                    }
                    Random r = new Random();
                    int randomNum = r.nextInt(foodList.length);
                    ToastHelper.toast("我不要你觉得,我要我觉得你要吃" + foodList[randomNum].toString());
                  },
                  child: const Text('预料之外意想之中')),
              glueDischargeFurnaceResult(listTitle)
            ],
          ),
        ),
      ),
    );
  }


  Widget glueDischargeFurnaceResult(List<Widget> listTitle) {
    return Expanded(
      flex: 1,
      child: Container(
        padding: const EdgeInsets.only(
            top: 20.0, bottom: 20.0, left: 10.0, right: 10.0),
        decoration: BoxDecoration(
            border:
            Border.all(color: Theme
                .of(context)
                .primaryColor, width: 10),
            borderRadius: BorderRadius.circular((5.0))),
        child: ListView(
          shrinkWrap: true,
          children:
          listTitle,
        ),
      ),
    );
  }


  Widget rich(int position) {
    return Container(
      decoration: BoxDecoration(
          border: Border.all(
              color: Theme
                  .of(context)
                  .primaryColor, width: 2),
          borderRadius: BorderRadius.circular((5.0))),
      child: Text.rich(TextSpan(
        children: [

          WidgetSpan(child: Padding(
            padding: const EdgeInsets.only( left: 10.0),
            child: Icon(Icons.favorite, color: Colors.red,),
          )),

          TextSpan(text: "    菜名:   ",
              style: TextStyle(
                  fontSize: 20,
                  color: Colors.black54
              )
          ),

          TextSpan(text: foodList.elementAt(position),
              style: TextStyle(
                  fontSize: 20,
                  color: Colors.black
              )
          )
        ],

      )),
    );}

  initData() {
    setState(() {
      listTitle = [];

      glueDischargeFurnaceResult(listTitle);
    });
  }

  initALLData() {
    setState(() {
      listTitle = [];
      foodList = [];
      glueDischargeFurnaceResult(listTitle);
    });
  }
}

用到的工具类为

import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';

const DEFAULT_TOAST_DURATION = Duration(seconds: 3);
const DEFAULT_TOAST_COLOR = Color(0xFF424242);

class ToastHelper {
  ToastHelper._internal();

  ///全局初始化Toast配置, child为MaterialApp
  static init(Widget child) {
    return OKToast(
      ///字体大小
      textStyle: TextStyle(fontSize: 16, color: Colors.white),
      backgroundColor: DEFAULT_TOAST_COLOR,
      radius: 10,
      dismissOtherOnShow: true,
      textPadding: EdgeInsets.fromLTRB(20, 10, 20, 10),
      child: child,
      duration: DEFAULT_TOAST_DURATION,
    );
  }

  static void toast(String msg,
      {Duration duration = DEFAULT_TOAST_DURATION,
        Color color = DEFAULT_TOAST_COLOR}) {
    showToast(msg, duration: duration, backgroundColor: color);
  }

  static void waring(String msg, {Duration duration = DEFAULT_TOAST_DURATION}) {
    showToast(msg, duration: duration, backgroundColor: Colors.yellow);
  }

  static void error(String msg, {Duration duration = DEFAULT_TOAST_DURATION}) {
    showToast(msg, duration: duration, backgroundColor: Colors.red);
  }

  static void success(String msg,
      {Duration duration = DEFAULT_TOAST_DURATION}) {
    showToast(msg, duration: duration, backgroundColor: Colors.lightGreen);
  }
}

不过记得下载好oktaost依赖