카테고리 없음

Nature웹 클론 및 클래스 연습

신승호. 2023. 2. 26. 22:37

1. 아래는 Nature의 웹사이트를 휴대폰으로 봤을 때의 화면이다. 어떻게 클래스를 제작할 것인지 고민하고 플러터로 구현하도록 하시오.

예제

  • 7개 이상의 News Article을 포함하도록 하시오.
  • 이 때 사용되는 뉴스 제목을 포함한 모든 데이터는 다음과 같다.
  •  
Journals adopt AI to spot duplicated images in manuscripts
/articles/d41586-021-03830-7
Smriti Mallapaty
23 Dec 2021


Fatal lab explosion in China highlights wider safety fears
/articles/d41586-021-03589-x
Andrew Silver
22 Dec 2021

Journals adopt AI to spot duplicated images in manuscripts
/articles/d41586-021-03807-6
Richard Van Noorden
21 Dec 2021

기사데이터 리스트

List<Map<String, dynamic>> articleData = [
  {
    'title':
        'Webb telescope blasts off successfully — launching a new era in astronomy',
    'url': 'https://www.nature.com/articles/d41586-021-03655-4',
    'author': 'Alexandra Witze',
    'createdDate': DateTime(25, 12, 2021), //이렇게 안하면 저장이 안됨;
    'img':
        'https://media.nature.com/w1248/magazine-assets/d41586-021-03655-4/d41586-021-03655-4_19975878.jpg?as=webp'
  },
  {
    'title': 'Journals adopt AI to spot duplicated images in manuscripts',
    'url': 'https://www.nature.com/articles/d41586-021-03830-7',
    'author': 'Smriti Mallapaty',
    'createdDate': DateTime(23, 12, 2021),
    'img':
        'https://media.nature.com/lw767/magazine-assets/d41586-021-03830-7/d41586-021-03830-7_19972466.jpg?as=webp'
  },
  {
    'title': 'Fatal lab explosion in China highlights wider safety fears',
    'url': 'https://www.nature.com/articles/d41586-021-03589-x',
    'author': 'Andrew Silver',
    'createdDate': DateTime(22, 12, 2021),
    'img':
        'https://media.nature.com/lw767/magazine-assets/d41586-021-03589-x/d41586-021-03589-x_19914056.jpg?as=webp'
  },
  {
    'title': 'Journals adopt AI to spot duplicated images in manuscripts',
    'url': 'https://www.nature.com/articles/d41586-021-03807-6',
    'author': 'Richard Van Noorden',
    'createdDate': DateTime(21, 12, 2021),
    'img':
        'https://media.nature.com/lw767/magazine-assets/d41586-021-03807-6/d41586-021-03807-6_19969478.jpg?as=webp'
  },
  {
    'title': 'Omicron overpowers key COVID antibody treatments in early tests',
    'url': 'https://www.nature.com/articles/d41586-021-03829-0',
    'author': 'Max Kozlov',
    'createdDate': DateTime(21, 12, 2021),
    'img':
        'https://media.nature.com/lw767/magazine-assets/d41586-021-03829-0/d41586-021-03829-0_19971408.jpg?as=webp'
  },
  {
    'title': 'Afghanistan’s academics despair months after Taliban takeover',
    'url': 'https://www.nature.com/articles/d41586-021-03774-y',
    'author': 'Smriti Mallapaty',
    'createdDate': DateTime(17, 12, 2021),
    'img':
        'https://media.nature.com/lw767/magazine-assets/d41586-021-03774-y/d41586-021-03774-y_19964192.jpg?as=webp'
  },
  {
    'title': 'The science events to watch for in 2022',
    'url': 'https://www.nature.com/articles/d41586-021-03772-0',
    'author': 'Davide Castelvecchi',
    'createdDate': DateTime(17, 12, 2021),
    'img':
        'https://media.nature.com/w1248/magazine-assets/d41586-021-03772-0/d41586-021-03772-0_19962224.jpg?as=webp'
  },
];

 

model 폴더안에 post.dart

class Post {
  String title;
  String url;
  String author;
  DateTime createdDate;
  String img;

  Post(
      {required this.title,
      required this.url,
      required this.author,
      required this.createdDate,
      required this.img});

  Post.fromMap(Map<String, dynamic> map)
      : title = map['title'],
        url = map['url'],
        author = map['author'],
        createdDate = map['createdDate'],
        img = map['img'];
}

widget폴더안에 post_card.dart

import 'package:assigment23/model/post.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class PostCard extends StatelessWidget {
  const PostCard(
      {super.key,
      required this.title,
      required this.imgUrl,
      required this.author,
      required this.createdDate});
  final String title;
  final String imgUrl;
  final String author;
  final DateTime createdDate;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Expanded(
                child: Text(
                  title,
                  style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      decoration: TextDecoration.underline),
                ),
              ),
              SizedBox(
                width: 30,
              ),
              Image.network(
                imgUrl,
                width: 150,
                height: 70,
              )
            ],
          ),
          SizedBox(
            height: 10,
          ),
          Text(
            author,
            style: TextStyle(color: Colors.black54),
          ),
          Row(
            children: [
              Text(
                'News |',
                style: TextStyle(
                    color: Colors.black,
                    fontWeight: FontWeight.bold,
                    fontSize: 20),
              ),
              Text(
                DateFormat('dd MM yyyy').format(createdDate),
                style: TextStyle(color: Colors.black54),
              )
            ],
          )
        ],
      ),
    );
  }
}

음 createdDate를 잘 모르겠다...

main.dart

import 'package:assigment23/articledata.dart';
import 'package:assigment23/model/post.dart';
import 'package:assigment23/widget/post_card.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MainPage(),
    );
  }
}

class MainPage extends StatefulWidget {
  MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

List<Post> dataList = articleData.map((e) => Post.fromMap(e)).toList();

class _MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
            child: Container(
      width: double.infinity,
      child: ListView.separated(
        itemCount: dataList.length,
        itemBuilder: (context, index) {
          return PostCard(
            title: dataList[index].title,
            imgUrl: dataList[index].img,
            author: dataList[index].author,
            createdDate: dataList[index].createdDate,
          );
        },
        separatorBuilder: (context, index) {
          return const Divider(
            thickness: 1,
          );
        },
      ),
    )));
  }
}

결과

Inkwell넣어서 url_launcher 패키지  사용해서 뉴스url에 들어가도록 만들수도 있는데 그것도 해야했나,,?

안나온 부분은 createdDate가 안나왔다. 

 

 

 

 

 

2.  다음 JSON으로 받아오는 네트워크 데이터를 이름있는 생성자 (fromMap)을 만드시오. 이 때, 제공되는 소스코드에서 빈 공간을 채워 다음의 화면을 구성할 수 있도록 하시오.

lib/model/userdata.dart

class UserData {

	///이곳 채우기.

}

lib/assignment23_page.dart

class Assignment23 extends StatefulWidget {
	const Assignment23({super.key});
	@override
	State<Assignment23> createState() => _Assignment23State();
}

class _Assignment23State extends State<Assignment23> {

	Future<Map<String, dynamic>> getJsonData() async {

		///이곳 채우기.

	}

	@override
	Widget build(BuildContext context) {
		return Scaffold(
			appBar: AppBar(title: Text('23일차 과제')),
			body: Center(
				child: FutureBuilder(
					future: getJsonData(),
					builder: (context, snapshot) {
						if (snapshot.connectionState == ConnectionState.waiting) {
							return const CupertinoActivityIndicator();
						}
						if (!snapshot.hasData) return const Text("데이터가 없습니다");
	
						Map<String, dynamic> data = snapshot.data as Map<String, dynamic>;
						List<dynamic> users = data['users'];
						List<dynamic> dismissDuplicatedUsers = _dismissDuplicatedData(users);
						return ListView.separated(
							itemBuilder: (context, index) {
								UserData userData = UserData.fromMap(dismissDuplicatedUsers[index]);
								return _buildItemWidget(userData);
							},
							separatorBuilder: (context, index) {
								return const Divider();
							},
							itemCount: dismissDuplicatedUsers.length,
						);
					}
				)
			),
		);
	}

	Widget _buildItemWidget(UserData userData) {
		return ListTile(
			leading: Image.network(userData.imageUrl),
			title: Text('${userData.firstName} ${userData.lastName}'),
			subtitle: Text('${userData.phoneNumber}'),
		);
	}

	List<dynamic> _dismissDuplicatedData(List<dynamic> data) {

		///이곳 채우기.

	}
}

지금 해보는중! 늦어서 일단 임시저장