0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SharedPreferencesを使って次のページに変数を渡す方法

Last updated at Posted at 2021-08-31

#Shared Preferencesとは
Shared Preferencesでは、データを保存・読み出しをできます。
しかし、どのようなデータでも保存できるわけではなく、保存できる型は決まっています。
保存できる型は、int型, double型, bool型, String型, String型のリストです。

まずはSharedPreferencesをインストールします。

pubspec.yaml
dependencies:
  shared_preferences: ^2.0.7

全てのコード

main.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:untitled/class2.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int num = 0;

  @override
  void initState() {
    super.initState();
    _loadCounter();
  }

  _loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      num = (prefs.getInt('number') ?? 0);
    });
  }

  _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      num ++;
    });
    prefs.setInt('number', num);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("title"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '$num',
              style: TextStyle(
                fontSize: 50,
              ),
            ),
            new RaisedButton(
              child: new Text("next"),
              onPressed: () {
                Navigator.push(context,
                    new MaterialPageRoute(builder: (context) => new Next()));
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        child: Icon(Icons.add),
      ),
    );
  }
}
class2.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Next extends StatefulWidget {
  @override
  _NextState createState() => _NextState();
}

class _NextState extends State<Next> {
  int num = 0;

  @override
  void initState() {
    super.initState();
    _loadCounter();
  }

  _loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      num = (prefs.getInt('number') ?? 0);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '$num',
              style: TextStyle(
                  color: Colors.black,
                  fontSize: 50
              ),
            ),
            RaisedButton(
              onPressed: () =>
                  Navigator.of(context, rootNavigator: true).pop(context),
              child: Text(
                'pop',
                style: TextStyle(
                    color: Colors.black
                ),
              ),)
          ],
        ),
      ),
    );
  }
}

参考:https://pub.dev/packages/shared_preferences/install

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?