简体   繁体   English

面对按钮 onclick 后通过 TextField 发生重复值的问题

[英]Facing an issue where duplication of values occurs through TextField after button onclick

I'm facing a problem when I add in a text value into my TextField it immediately gets duplicated once I save it and redirect it back to the Home screen through the save button onclick.当我将文本值添加到我的 TextField 中时,我遇到了一个问题,一旦我保存它并通过保存按钮 onclick 将其重定向回主屏幕,它就会立即被复制。

The video link for a better view of the error:更好地查看错误的视频链接:

https://youtu.be/jtujDoXzL7o https://youtu.be/jtujDoXzL7o

The entire code:整个代码:

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

TextEditingController _notesController1 = new TextEditingController();
TextEditingController _notesController2 = new TextEditingController();
final data = [];

void main() => runApp(MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),
    ));

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return (Scaffold(
      backgroundColor: Colors.blueGrey[700],
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text(
          'Glass',
          style: TextStyle(
            fontSize: 20.0,
            letterSpacing: 1.0,
            color: Colors.white,
            fontFamily: 'Montserrat',
          ),
        ),
        centerTitle: true,
        backgroundColor: Colors.blueGrey[700],
      ),
      body: ListView.builder(
        padding: const EdgeInsets.only(top: 10.0),
        itemCount: data.length,
        itemBuilder: (context, index) {
        return GestureDetector(
          child:Card(
            child:Padding(
            padding: const EdgeInsets.only(top: 12.0, bottom: 10, left: 10.0, right: 10.0),
          child: ListTile(
            dense: true,
            onTap:() {},
            title: Text(
              data[index],
              overflow: TextOverflow.ellipsis,
            ),
          ), 
          ),
          ),
        );
       },
      ), 
      floatingActionButton: FloatingActionButton(
              elevation: 9.0,
        child: Icon(Icons.add),
        onPressed: () async {
          await Navigator.push(
            context, MaterialPageRoute(builder: (context) => SharedPreference1()));
        },
        backgroundColor: Colors.blueGrey[300],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    ));
  }
}

Future<bool> saveData(String nameKey, String value) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    return await preferences.setString(nameKey, value);
  }
Future<String> loadData(String nameKey) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    return preferences.getString(nameKey);
  }

class Hero extends State<SharedPreference1> {
  Widget buildSaveButton(context) {
  return Container(
    color: Colors.blueGrey[700],
    margin: EdgeInsets.only(top:340.0),
    child: RaisedButton.icon(
      elevation: 9.0,
      icon: Icon(Icons.save),
      label: Text('Save'),
      color: Colors.white,
      onPressed: () async {
        await saveData("_key_name", _notesController1.text);
        await setData();
        print(data);
        Navigator.push(context, MaterialPageRoute(builder: (context) => Home()));
              },
            ),
          ); 
        }      
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        color: Colors.blueGrey[700],
        child: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                buildHeading(context),
                buildNotesText(),
                buildSaveButton(context),
              ],
            ),
          ),
        ),
      ),
    );
  }
  @override
  void initState() {
    super.initState();
    setData();
  }

  setData() {
    loadData("_key_name").then((value) {
      setState(() {
        if(value==null){
          print("Value not available.");
        }
        else{
          data.add(value);
        }
        
      });
    });
  }

}

Widget buildHeading(context) {
  return Material(
    color: Colors.blueGrey[700],
    child: Padding(
      padding: const EdgeInsets.only(left: 20.0, top: 10.0),
      child: Row(
        children: <Widget>[
          Expanded(
            child: TextField(
              maxLines: 1,
              controller: _notesController1,
              decoration: InputDecoration(
                border: InputBorder.none,
                hintText: 'Note Title',
              ),
              style: TextStyle(
                fontSize: 20, 
                color: Colors.white, 
                fontFamily: 'Montserrat',
                ),
            ),
          ),
          FlatButton(
            child: Icon(Icons.close, color: Colors.white, size: 27),
            onPressed: () {
              Navigator.of(context).pop();
            },
          )
        ],
      ),
    ),
  );
}

Widget buildNotesText() {
  return Material(
    color: Colors.blueGrey[700],
    child: Padding(
      padding: const EdgeInsets.all(20.0),
      child: TextField(
        maxLines: null,
        controller: _notesController2,
        decoration: InputDecoration(
          border: InputBorder.none,
          hintText: 'Create Note Here',
        ),
        cursorColor: Colors.white,
        autofocus: true,
        style: TextStyle(color: Colors.white,fontSize: 18,fontFamily: 'Montserrat'),
      ),
    ),
  );
}

class SharedPreference1 extends StatefulWidget {
  SharedPreference1() : super(); 
  @override
  Hero createState() => Hero();
}

The buildHeading widget is where the title of the notes will be inputted. buildHeading小部件是输入笔记标题的地方。

The Hero class is where the save button is made which will then save the value to the list and immediately be displayed to the Home screen which is the Home/_HomeState class. Hero class 是保存按钮的位置,然后将值保存到列表中并立即显示到主屏幕,即Home/_HomeState class。

You're calling setData on initState for Hero widget, that's the reason why you see duplicated values.您正在为Hero小部件调用initState上的setData ,这就是您看到重复值的原因。 The value on SharedPreferences will be added to data every time you open Hero widget.每次打开Hero小部件时, SharedPreferences上的值都会添加到data中。

Don't see this call makes sense as you want to call this method when onPressed is executed and you're already doing it.没有看到这个调用有意义,因为你想在执行onPressed时调用这个方法并且你已经在这样做了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM