如何在main.dart中包含单独的文件

时间:2019-01-23 18:56:35

标签: flutter tabbed

在Flutter,我并不陌生,请尝试学习它。我将代码添加到单独的页面,并将其从main.dart文件中拉出。首先,我需要在我的主页main.dart中添加一个gridview。我在做错事,但找不到。

import 'package:flutter/material.dart';
import './firstpage.dart' ;
import './secondpage.dart';
import './thirdpage.dart' ;
import './fourthpage.dart';
import './fifthpage.dart' ;


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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  TabController controller;

  @override
  void initState() {
    super.initState();
    controller = new TabController(vsync: this, length: 5);
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Test App"),
        backgroundColor: Colors.teal,
      ),
      bottomNavigationBar: new Material(
        color: Colors.teal,
        child: new TabBar(
          controller: controller,
          tabs: <Widget>[
            new Tab(icon: new Icon(Icons.home)),
            new Tab(icon: new Icon(Icons.calendar_today)),
            new Tab(icon: new Icon(Icons.library_music)),
            new Tab(icon: new Icon(Icons.camera)),
            new Tab(icon: new Icon(Icons.more)),
          ],
        ),
      ),
      body: new TabBarView(controller: controller, children: <Widget>[
        new MyApp2(),
        new SecondPage(),
        new ThirdPage(),
        new FourthPage(),
        new FifthPage(),
      ]),
    );
  }
}

我有一个首页,我正在从名为firstpage.dart的文件中调用

import 'dart:async';
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<List<Photo>> fetchPhotos(http.Client client) async {
  final response =
      await client.get('https://jsonplaceholder.typicode.com/photos');

  // Use the compute function to run parsePhotos in a separate isolate
  return compute(parsePhotos, response.body);
}

// A function that will convert a response body into a List<Photo>
List<Photo> parsePhotos(String responseBody) {
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}

class Photo {
  final int albumId;
  final int id;
  final String title;
  final String url;
  final String thumbnailUrl;

  Photo({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});

  factory Photo.fromJson(Map<String, dynamic> json) {
    return Photo(
      albumId: json['albumId'] as int,
      id: json['id'] as int,
      title: json['title'] as String,
      url: json['url'] as String,
      thumbnailUrl: json['thumbnailUrl'] as String,
    );
  }
}



class MyApp2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Isolate Demo';

    return MaterialApp(
      title: appTitle,
      home: MyHomePage2(title: appTitle),
    );
  }
}

class MyHomePage2 extends StatelessWidget {
  final String title;

  MyHomePage2({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      
      child: FutureBuilder<List<Photo>>(
        future: fetchPhotos(http.Client()),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);

          return snapshot.hasData
              ? PhotosList(photos: snapshot.data)
              : Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

class PhotosList extends StatelessWidget {
  final List<Photo> photos;

  PhotosList({Key key, this.photos}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
      ),
      itemCount: photos.length,
      itemBuilder: (context, index) {
        return Image.network(photos[index].thumbnailUrl);
      },
    );
  }
}

似乎2个应用程序栏,顶部有一个间隙,我做错了什么?

1 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,这是预期的结果:

Expected result

您可以在下面找到代码。如果我已正确理解您的问题,则无需将MyHomePage2包装到MaterialApp小部件中。因此,除非有充分的理由要使用两个MyApp2小部件,否则不需要小部件MaterialApp。 通常,您只想在应用中使用一个MaterialApp小部件。

import 'package:flutter/material.dart';
import './firstpage.dart' ;
import './secondpage.dart';
import './thirdpage.dart' ;
import './fourthpage.dart';
import './fifthpage.dart' ;


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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  TabController controller;

  @override
  void initState() {
    super.initState();
    controller = new TabController(vsync: this, length: 5);
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Test App"),
        backgroundColor: Colors.teal,
      ),
      bottomNavigationBar: new Material(
        color: Colors.teal,
        child: new TabBar(
          controller: controller,
          tabs: <Widget>[
            new Tab(icon: new Icon(Icons.home)),
            new Tab(icon: new Icon(Icons.calendar_today)),
            new Tab(icon: new Icon(Icons.library_music)),
            new Tab(icon: new Icon(Icons.camera)),
            new Tab(icon: new Icon(Icons.more)),
          ],
        ),
      ),
      body: new TabBarView(controller: controller, children: <Widget>[
        new MyHomePage2(),
        new SecondPage(),
        new ThirdPage(),
        new FourthPage(),
        new FifthPage(),
      ]),
    );
  }
}