前回までにMyAppとInputPageという2つのStatelessウィジェットを作成しました。
今回はInputPageとMyAppの内容を抽出して、新たに名称をListPageとして変更して分割します。
そしてMyAppからListPageを呼び出すように変更していきます。
まずはInputPageを分割していきます。
InputPageは以下のようになるんですが、コードを見るとMaterialAppはMyAppでも使われています。
import 'package:flutter/material.dart';
class InputPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Input Page'),
),
body: Column(
children: [
SizedBox(height: 4.0,),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15.0),
),
labelText: 'Dog Name',
),
),
SizedBox(height: 4.0,),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15.0),
),
labelText: 'Dog Age',
),
),
],
),
),
);
}
}
その場合はMaterialAppを省略して少しでもコードを短くしていきます。
import 'package:flutter/material.dart';
class InputPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Input Page'),
),
body: Column(
children: [
SizedBox(height: 4.0,),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15.0),
),
labelText: 'Dog Name',
),
),
SizedBox(height: 4.0,),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15.0),
),
labelText: 'Dog Age',
),
),
],
),
);
}
}
上記のコードをinput_page.dartとして保存します。
次にMyAppのScaffold以下をListPageに名称を変更して分割します。
import 'package:flutter/material.dart';
class ListPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dog List'),
),
body: ListView(
children: [
ListTile(
title: Text('name 1'),
subtitle: Text('age 1'),
),
ListTile(
title: Text('name 2'),
subtitle: Text('age 2'),
),
ListTile(
title: Text('name 3'),
subtitle: Text('age 3'),
),
],
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {},
),
);
}
}
MyAppの内容を抽出してListPageに変更して、InputPageと同様にMaterialAppを省略して上記のコードをlist_page.dartとして保存します。
最後にMyAppからListPageを呼び出すようにコードを変更していきます。
import 'package:dog_list_app/list_page.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: ListPage(),
),
);
}
}
AppBarは分割したそれぞれのファイルに入っているので省略して、body内にlist_page.dartの中のListPageを参照することを指定します。
またlist_page.dartをimportして参照できるようにしておきます。
これでファイルを分割することができました。
現在、main.dartとlist_page.dartとinput_page.dartと3つのファイルができているはずです。
今後は新しいStatelessウィジェットは新たなファイルで作成していきます。
次回はListPageのフローティングボタンからInputPageに移動できるようにします。
コメント