简体   繁体   中英

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. 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. 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.

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.

Any time you create a controller it needs to be created and disposed of properly (normally in your initState and dispose methods).

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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