https://flutter-ko.dev/docs/cookbook/navigation/passing-data
새로운 화면으로 데이터 보내기
종종 새로운 화면으로 단순히 이동하는 것 뿐만 아니라 데이터를 넘겨주어야 할 때도 있습니다. 예를 들어, 사용자가 선택한 아이템에 대한 정보를 같이 넘겨주고 싶은 경우가 있습니다.기억하
flutter-ko.dev
저 링크에 나온대로 코딩하면 null관련 에러가 나와서 일부 수정해서 테스트함.
import 'package:flutter/material.dart';
class Todo {
final String title;
final String description;
Todo(this.title, this.description);
}
void main() {
runApp(MaterialApp(
title: 'Passing Data',
home: TodosScreen(
todos: List.generate(
1000,
(i) => Todo(
'Todo $i',
'A description of what needs to be done for Todo $i',
),
),
),
));
}
class TodosScreen extends StatelessWidget {
final List<Todo> todos;
const TodosScreen({ Key? key, required this.todos}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Todos'),
),
body: ListView.builder(
itemCount: todos.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(todos[index].title),
// 사용자가 ListTile을 선택하면, DetailScreen으로 이동합니다.
// DetailScreen을 생성할 뿐만 아니라, 현재 todo를 같이 전달해야
// 한다는 것을 명심하세요.
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(todo: todos[index], key: null,),
),
);
},
);
},
),
);
}
}
class DetailScreen extends StatelessWidget {
// Todo를 들고 있을 필드를 선언합니다.
final Todo todo;
// 생성자는 Todo를 인자로 받습니다.
const DetailScreen({ Key? key, required this.todo}) : super(key: key);
@override
Widget build(BuildContext context) {
// UI를 그리기 위해 Todo를 사용합니다.
return Scaffold(
appBar: AppBar(
title: Text(todo.title),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(todo.description),
),
);
}
}
샘플소스에 있던 라인
TodosScreen({Key key, @required this.todos}) : super(key: key);
2.12이후에는 아래와 같이 변경해야 에러가 안남
const TodosScreen({ Key? key, required this.todos}) : super(key: key);
Key하고 this.todos가 초기화 안되었다고 에러가 나왔던것 같음.
2.12 이후 부터 nullSafety가 적용되었다고 하던데.. 암튼 ?(question mark)의 의미는 명시적으로 널을 허용해주는것
Dart 2.12부터 @required주석은 이제 required키워드로 대체되었다고 함.
required는 다른 사람들이 값을 전달해야 하는 경우 필드를 표시해야 한다고 함.
'밥벌이 > flutter' 카테고리의 다른 글
[22.04.09] http api 호출 (0) | 2022.04.09 |
---|---|
[22.04.08] flutter 이전화면에 데이터 전달하기 (0) | 2022.04.09 |
[22.04.07] flutter inspection을 이용한 디버깅 (0) | 2022.04.08 |
[22/04/06] [flutter] flutter_login 샘플 분석 (0) | 2022.04.08 |
[22.04.05] [flutter]Business Logic Component (BLOC) (0) | 2022.04.06 |