简体   繁体   English

Flutter 中的按钮 onclick 面临问题

[英]Facing an issue with button onclick in Flutter

I'm not 100% sure on how to best explain this issue but I will try my best.我不能 100% 确定如何最好地解释这个问题,但我会尽力而为。 The problem I'm facing is whenever I click the button on the emulator to go to the next page, I get faced with a lot of errors but the app itself functions properly without any issues, only when the button is clicked the errors appear on the terminal.我面临的问题是,每当我单击模拟器上的按钮到 go 到下一页时,我都会遇到很多错误,但应用程序本身可以正常运行而没有任何问题,只有当单击按钮时才会出现错误终点站。 The errors are shown below:错误如下所示:

E/dalvikvm( 1787): Could not find class 'android.view.inputmethod.CursorAnchorInfo$Builder', referenced from method io.flutter.plugin.editing.InputConnectionAdaptor.finishComposingText

W/dalvikvm( 1787): VFY: unable to resolve new-instance 411 (Landroid/view/inputmethod/CursorAnchorInfo$Builder;) in Lio/flutter/plugin/editing/InputConnectionAdaptor;

D/dalvikvm( 1787): VFY: replacing opcode 0x22 at 0x000e

D/dalvikvm( 1787): DexOpt: unable to opt direct call 0x0846 at 0x10 in Lio/flutter/plugin/editing/InputConnectionAdaptor;.finishComposingText

These errors pop up when the button is clicked on the home page.在主页上单击按钮时会弹出这些错误。 The code is below:代码如下:

The button code for the home page:主页按钮代码:

onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => SharedPreference1())); },

The button leads to another screen where the input into the TextField is handled, which works perfectly but the error is when the button which is clicked beforehand in the Home class.该按钮通向另一个屏幕,在该屏幕中处理输入到 TextField 中的内容,该屏幕运行良好,但错误是在Home class 中预先单击该按钮时。

The whole code is below:整个代码如下:

import 'package:shared_preferences/shared_preferences.dart';

TextEditingController _notesController1 = new TextEditingController();
TextEditingController _notesController2 = new TextEditingController();
List<String> data = [];

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

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return (Scaffold(
      drawer: Drawer(
        child: ListView(
          children: <Widget>[
            ListTile(
              title: Text(
                'Glass',
                style: TextStyle(
                  fontSize: 15.0,
                  letterSpacing: 1.0,
                  color: Colors.black,
                  fontFamily: 'Montserrat',
                ),
              ),
            ),
            ListTile(
              title: Text('Trash'),
            ),
          ],
        ),
      ),
      backgroundColor: Colors.blueGrey[700],
      appBar: AppBar(
        title: Text(
          'Glass',
          style: TextStyle(
            fontSize: 20.0,
            letterSpacing: 1.0,
            color: Colors.white,
            fontFamily: 'Montserrat',
          ),
        ),
        centerTitle: true,
        backgroundColor: Colors.blueGrey[700],
      ),
      floatingActionButton: FloatingActionButton(
              elevation: 9.0,
        child: Icon(Icons.add),
        onPressed: () {
          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", _notesController2.text);
        await setData();
        print(data);
              },
            ),
          ); 
        }
  @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();
}```

I'm not exactly sure what's causing the error but there are some things from your code that should be changed.我不确定是什么导致了错误,但您的代码中有一些内容应该更改。 You should always contain methods and variables inside of classes or else they are in the global scope and are never disposed.您应该始终在类中包含方法和变量,否则它们在全局 scope 中并且永远不会被释放。

Any time you create a controller it needs to be created and disposed of properly (normally in your initState and dispose methods).每当您创建 controller 时,都需要正确创建和处置它(通常在您的initStatedispose方法中)。

I've refactored your code a little to include all global scoped methods/variables in your classes.我对您的代码进行了一些重构,以在您的类中包含所有全局范围的方法/变量。 See if this solves your problem.看看这是否能解决您的问题。

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

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),
    ),
  );
}

class Hero extends State<SharedPreference1> {
  TextEditingController _notesController1;
  TextEditingController _notesController2;
  List<String> data = [];

  @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),
              ],
            ),
          ),
        ),
      ),
    );
  }

  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'),
        ),
      ),
    );
  }

  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", _notesController2.text);
          await setData();
          print(data);
        },
      ),
    );
  }

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

  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 Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return (Scaffold(
      drawer: Drawer(
        child: ListView(
          children: <Widget>[
            ListTile(
              title: Text(
                'Glass',
                style: TextStyle(
                  fontSize: 15.0,
                  letterSpacing: 1.0,
                  color: Colors.black,
                  fontFamily: 'Montserrat',
                ),
              ),
            ),
            ListTile(
              title: Text('Trash'),
            ),
          ],
        ),
      ),
      backgroundColor: Colors.blueGrey[700],
      appBar: AppBar(
        title: Text(
          'Glass',
          style: TextStyle(
            fontSize: 20.0,
            letterSpacing: 1.0,
            color: Colors.white,
            fontFamily: 'Montserrat',
          ),
        ),
        centerTitle: true,
        backgroundColor: Colors.blueGrey[700],
      ),
      floatingActionButton: FloatingActionButton(
        elevation: 9.0,
        child: Icon(Icons.add),
        onPressed: () {
          Navigator.push(context,
              MaterialPageRoute(builder: (context) => SharedPreference1()));
        },
        backgroundColor: Colors.blueGrey[300],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    ));
  }
}

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

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

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