【问题标题】:Flutter Userinput will only get displayed after a hotreload, but not in the application itselfFlutter 用户输入只会在热重载后显示,但不会在应用程序本身中显示
【发布时间】:2022-07-12 00:05:53
【问题描述】:

您好,我是 Flutter 和编码的新手,并尝试构建我的第一个应用程序。我创建了一个 textformfield 以在上面的容器中使用按钮添加新的待办事项。我使用 texteditingcontroller 来获取用户输入并将输入存储在一个变量中。我试图在 toDoSection 上显示 userInput,但只有在我热重新加载应用程序时才会出现。我的按钮,应该做的工作,而不是工作。我在这里做错了什么?

landing_page.dart

import 'package:flutter/material.dart';
import 'package:flutter_application_1/presentation/widgets/to_do_section.dart';

 final _textController = TextEditingController();
    String userInput = "";
class LandingPage extends StatefulWidget {
  const LandingPage({Key? key}) : super(key: key);

  @override
  State<LandingPage> createState() => _LandingPageState();
}

class _LandingPageState extends State<LandingPage> {
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      
      appBar: AppBar(
        title: const Center(child: Text("To-Do-App")),
        backgroundColor: Colors.redAccent,
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            const ToDos(),
            ToDoAdd()
            ],
        ),
      ),
    );
  }

 

  Column ToDoAdd() {
    return Column(
          children:  [
            Padding(
              padding: EdgeInsets.only(top: 8.0, left: 20, right: 20, bottom: 20),
              child: TextField(
                controller: _textController,
                textAlign: TextAlign.center,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: "Add a new ToDo",
                )  ,
              ),
              
            ),
            MaterialButton(
              color: Colors.redAccent,
                onPressed: () {
                  setState(() {
                  userInput = _textController.text; 
                  toDoList.add(userInput);
                  
                });
                  
                },
                child: Text("Admit", style: TextStyle(color: Colors.white),),
                ),
                Text(userInput)
          ],
        );
  }


}

to_do_section.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_application_1/presentation/widgets/landing_page.dart';
import 'package:flutter_application_1/responsive_layout.dart';

var toDoList = <String> [userInput];
class ToDos extends StatefulWidget {
  
  const ToDos({Key? key, }) : super(key: key);

  @override
  State<ToDos> createState() => _ToDosState();
}

class _ToDosState extends State<ToDos> {
  
  
  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    return Padding(
      padding: EdgeInsets.only(
          top: SizeConfig.blockSizeHorizontal * 10,
          left: SizeConfig.blockSizeVertical * 2.5,
          right: SizeConfig.blockSizeVertical * 2.5,
          bottom: SizeConfig.screenHeight / 8
          ),
      child: SizedBox(
        width: SizeConfig.blockSizeHorizontal*100,
        height: SizeConfig.blockSizeVertical*40,
        child: Container(
          decoration: BoxDecoration(
              color: Colors.grey[400],
              borderRadius: BorderRadius.circular(30),
              border: Border.all(
                  color: Colors.black45, style: BorderStyle.solid, width: 4)),
          child: Padding(
            padding:  EdgeInsets.all(8.0),
            child: Column(
              children: [
                   Text(userInput)               
                ]),
          ),
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter dart mobile


    【解决方案1】:

    下面的代码应该可以解决问题。问题是没有使用setState 用新数据刷新屏幕,也没有遍历所有值来显示它们(另外,将全局变量移动到本地)。

    查看live demo on DartPad

    还有代码:

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const LandingPage(),
        );
      }
    }
    
    class LandingPage extends StatefulWidget {
      const LandingPage({Key? key}) : super(key: key);
    
      @override
      State<LandingPage> createState() => _LandingPageState();
    }
    
    class _LandingPageState extends State<LandingPage> {
      String userInput = "";
      var toDoList = <String>[];
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Center(child: Text("To-Do-App")),
            backgroundColor: Colors.redAccent,
          ),
          body: SingleChildScrollView(
            child: Column(
              children: [ToDos(list: toDoList), ToDoAdd()],
            ),
          ),
        );
      }
    
      Column ToDoAdd() {
        return Column(
          children: [
            Padding(
              padding:
                  const EdgeInsets.only(top: 8.0, left: 20, right: 20, bottom: 20),
              child: TextField(
                onChanged: (value) => setState(() => userInput = value),
                textAlign: TextAlign.center,
                decoration: const InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: "Add a new ToDo",
                ),
              ),
            ),
            MaterialButton(
              color: Colors.redAccent,
              onPressed: () => setState(() => toDoList.add(userInput)),
              child: const Text(
                "Admit",
                style: TextStyle(color: Colors.white),
              ),
            ),
            Text(userInput)
          ],
        );
      }
    }
    
    class ToDos extends StatefulWidget {
      final List<String> list;
      const ToDos({
        Key? key,
        required this.list,
      }) : super(key: key);
    
      @override
      State<ToDos> createState() => _ToDosState();
    }
    
    class _ToDosState extends State<ToDos> {
      @override
      Widget build(BuildContext context) {
        SizeConfig().init(context);
        return Padding(
          padding: EdgeInsets.only(
              top: SizeConfig.blockSizeHorizontal * 10,
              left: SizeConfig.blockSizeVertical * 2.5,
              right: SizeConfig.blockSizeVertical * 2.5,
              bottom: SizeConfig.screenHeight / 8),
          child: SizedBox(
            width: SizeConfig.blockSizeHorizontal * 100,
            height: SizeConfig.blockSizeVertical * 40,
            child: Container(
              decoration: BoxDecoration(
                  color: Colors.grey[400],
                  borderRadius: BorderRadius.circular(30),
                  border: Border.all(
                      color: Colors.black45, style: BorderStyle.solid, width: 4)),
              child: Padding(
                padding: EdgeInsets.all(8.0),
                child: Column(children: [
                  for (final value in widget.list)
                    Text(value),
                ]),
              ),
            ),
          ),
        );
      }
    }
    
    class SizeConfig {
      static late MediaQueryData _mediaQueryData;
      static late double screenWidth;
      static late double screenHeight;
      static late double blockSizeHorizontal;
      static late double blockSizeVertical;
      static late double _safeAreaHorizontal;
      static late double _safeAreaVertical;
      static late double safeBlockHorizontal;
      static late double safeBlockVertical;
    
      void init(BuildContext context) {
        _mediaQueryData = MediaQuery.of(context);
        screenWidth = _mediaQueryData.size.width;
        screenHeight = _mediaQueryData.size.height;
        blockSizeHorizontal = screenWidth / 100;
        blockSizeVertical = screenHeight / 100;
        _safeAreaHorizontal =
            _mediaQueryData.padding.left + _mediaQueryData.padding.right;
        _safeAreaVertical =
            _mediaQueryData.padding.top + _mediaQueryData.padding.bottom;
        safeBlockHorizontal = (screenWidth - _safeAreaHorizontal) / 100;
        safeBlockVertical = (screenHeight - _safeAreaVertical) / 100;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 2021-04-09
      • 2016-11-21
      • 1970-01-01
      • 2020-03-10
      相关资源
      最近更新 更多