シェルスクリプトマガジン

特集2 FlutterでGUIアプリを開発しよう(Vol.79記載)

著者:三好 文二郎

「Flutter」は、米Google社がOSS(オープンソースソフトウエア)として提供する、GUI アプリ開発用のSDK(Software Development Kit)です。単一のコードで複数のプラットフォーム向けのGUIアプリを作成できるほか、標準で用意されるUIコンポーネントが豊富、Hot Reloadによる開発者体験が素晴らしいことなどから開発者の間で人気が高まっています。Flutterの概要と、Flutterを利用したアプリ開発方法について紹介します。

シェルスクリプトマガジン Vol.79は以下のリンク先でご購入できます。

図18 ウィジェットに関する記述の例

children: <Widget>[
  const Text(
    'You have pushed the button this many times:',
  ),
  Text(
    '$_counter',
    style: Theme.of(context).textTheme.headline4,
  ),
],

図19 ボタンウィジェットを追加するコードの例

children: <Widget>[
  const Text(
    'You have pushed the button this many times:',
  ),
  Text(
    '$_counter',
    style: Theme.of(context).textTheme.headline4,
  ),
  MaterialButton (
    color: Colors.cyan.withOpacity(0.7),
    shape: RoundedRectangleBorder(borderRadius:BorderRadius.circular(30.0)),
    onPressed: () {},
    child: const Text('this is a button widget'),
  ),
],

図21 my_first_appプロジェクトの「pubspec.yaml」ファイルの内容

name: my_first_app
description: A new Flutter project.
publish_to: "none"
version: 1.0.0+1
environment:
  sdk: ">=2.16.2 <3.0.0"
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0
flutter:
  uses-material-design: true

図22 go_routerパッケージを利用する場合の記述例

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  go_router: ^3.1.1

図23 画面を追加するためのコード

class NavigatedPage extends StatelessWidget {
  const NavigatedPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('navigated page'),
      ),
      body: const Center(
        child: Text('navigated with go_router'),
      ),
    );
  }
}

図24 画面遷移のためのコード

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);
  final _router = GoRouter(
    routes: [
      GoRoute(
        path: '/',
        builder: (context, state) =>
          const MyHomePage(title: 'Flutter Demo Home Page'),
      ),
      GoRoute(
        path: '/navigated',
        builder: (context, state) => const NavigatedPage(),
      ),
    ],
  );

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
    ),
    routeInformationParser: _router.routeInformationParser,
    routerDelegate: _router.routerDelegate);
  }
}

図25 ボタンウィジェットに画面遷移処理を割り当てるコード

MaterialButton (
  color: Colors.cyan.withOpacity(0.7),
  shape: RoundedRectangleBorder(borderRadius:BorderRadius.circular(30.0)),
  onPressed: () {
    GoRouter.of(context).go('/navigated');
  },
  child: const Text('Navigate'),
),

図26 main()関数のコードを変更

void main() {
  runApp(MyApp());
}