无法将参数类型“上下文”分配给参数类型“ BuildContext”-Flutter

时间:2020-03-27 23:43:46

标签: flutter dart

我在上下文中遇到错误,我在stackoverflow上也发现了类似的问题,但是并没有解决我的问题。该问题的答案建议添加import 'package:path/path.dart';,但仍然出现相同的错误。这是我的代码如下:

import 'dart:js';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:chewie/chewie.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:fluttershare/models/user.dart';
import 'package:fluttershare/pages/comments.dart';
import 'package:fluttershare/pages/home.dart';
import 'package:fluttershare/widgets/progress.dart';
import 'package:video_player/video_player.dart';
import 'package:path/path.dart';

class Post extends StatefulWidget {
  final String postId;
  final String ownerId;
  final String username;
  final String foodname;
  final String placename;
  final String cityname;
  final String statename;
  final String mediaUrl;
  final double rating;
  final dynamic likes;

  Post({
    this.postId,
    this.ownerId,
    this.username,
    this.foodname,
    this.placename,
    this.cityname,
    this.statename,
    this.mediaUrl,
    this.rating,
    this.likes,
  });

  factory Post.fromDocument(DocumentSnapshot doc) {
    return Post(
      postId: doc['postId'],
      ownerId: doc['ownerId'],
      username: doc['username'],
      foodname: doc['foodname'],
      placename: doc['placename'],
      cityname: doc['cityname'],
      statename: doc['statename'],
      mediaUrl: doc['mediaUrl'],
      rating: doc['rating'],
      likes: doc['likes'],
    );
  }

  int getLikeCount(likes) {
    if (likes == null) {
      return 0;
    }
    int count = 0;
    likes.values.forEach((val) {
      if (val == true) {
        count += 1;
      }
    });
    return count;
  }

  @override
  _PostState createState() => _PostState(
        postId: this.postId,
        ownerId: this.ownerId,
        username: this.username,
        foodname: this.foodname,
        placename: this.placename,
        cityname: this.cityname,
        statename: this.statename,
        mediaUrl: this.mediaUrl,
        likes: this.likes,
        likeCount: getLikeCount(this.likes),
      );
}

class _PostState extends State<Post> {
  final String currentUserId = currentUser?.id;
  final String postId;
  final String ownerId;
  final String username;
  final String foodname;
  final String placename;
  final String cityname;
  final String statename;
  final String mediaUrl;
  String rating;
  int likeCount;
  Map likes;
  bool isLiked;

  _PostState({
    this.postId,
    this.ownerId,
    this.username,
    this.foodname,
    this.placename,
    this.cityname,
    this.statename,
    this.mediaUrl,
    this.rating,
    this.likes,
    this.likeCount,
  });

  buildPostHeader() {
    return FutureBuilder(
      future: usersRef.document(ownerId).get(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return circularProgress();
        }
        User user = User.fromDocument(snapshot.data);
        return ListTile(
          leading: CircleAvatar(
            backgroundImage: CachedNetworkImageProvider(user.photoUrl),
            backgroundColor: Colors.grey,
          ),
          title: GestureDetector(
            onTap: () => print('showing profile'),
            child: Text(
              user.username,
              style: TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          trailing: IconButton(
            onPressed: () => print('deleting post'),
            icon: Icon(Icons.more_vert),
          ),
        );
      },
    );
  }

  VideoPlayerController _controller;
  Future<void> _initializeVideoPlayerFuture;

  @override
  void initState() {
    _controller = VideoPlayerController.network(mediaUrl);
    _initializeVideoPlayerFuture = _controller.initialize();
    _controller.setLooping(true);
    _controller.setVolume(1.0);
    super.initState();
  }

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

  //                                     Post Chewie Display...

  buildPostImage() {
    return FittedBox(
      fit: BoxFit.contain,
      child: mounted
          ? Chewie(
              controller: ChewieController(
                videoPlayerController: _controller,
                aspectRatio: 16 / 9,
                autoPlay: false,
                autoInitialize: true,
                looping: true,
              ),
            )
          : Container(),
    );
  }

  handleLikePost() {
    bool _isLiked = likes[currentUserId] == true;

    if (_isLiked) {
      postsRef
          .document(ownerId)
          .collection('userPosts')
          .document(postId)
          .updateData({'likes.$currentUserId': false});
      setState(() {
        likeCount -= 1;
        isLiked = false;
        likes[currentUserId] = false;
      });
    } else if (!_isLiked) {
      postsRef
          .document(ownerId)
          .collection('userPosts')
          .document(postId)
          .updateData({'likes.$currentUserId': true});
      setState(() {
        likeCount += 1;
        isLiked = true;
        likes[currentUserId] = true;
      });
    }
  }

  buildPostFooter() {
    return Column(
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Padding(padding: EdgeInsets.only(top: 40.0, left: 20.0)),
            GestureDetector(
              onTap: handleLikePost,
              child: Icon(
                isLiked ? Icons.favorite : Icons.favorite_border,
                size: 28.0,
                color: Colors.red,
              ),
            ),
            Padding(padding: EdgeInsets.only(right: 20.0)),
            GestureDetector(
              onTap: () => showComments(
                context,
                postId: postId,
                ownerId: ownerId,
                mediaUrl: mediaUrl,
              ),
              child: Icon(
                Icons.supervised_user_circle,
                size: 28.0,
                color: Colors.blueAccent,
              ),
            ),
            Padding(padding: EdgeInsets.only(right: 50.0)),
            Icon(Icons.location_on, color: Colors.blueAccent),
            Container(
              margin: EdgeInsets.only(left: 2.0, top: 5.0, right: 10.0),
              child: Text("$cityname " + "$statename",
                  style: TextStyle(color: Colors.blueAccent)),
            ),
          ],
        ),
        Row(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(left: 20.0),
              child: Text(
                "$likeCount likes",
                style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(left: 20.0, top: 10.0, bottom: 5.0),
              child: Text(
                "$foodname ",
                style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(padding: EdgeInsets.only(left: 20.0)),
            Icon(
              Icons.restaurant,
              color: Colors.blueAccent,
            ),
            Container(
              color: Colors.blueAccent,
              padding: EdgeInsets.all(5.0),
              margin: EdgeInsets.only(left: 2.0),
              child: Text(placename.toUpperCase(),
                  style: TextStyle(color: Colors.white)),
            ),
          ],
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    isLiked = (likes[currentUserId] == true);
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        buildPostHeader(),
        buildPostImage(),
        buildPostFooter(),
        Divider(),
        Padding(padding: EdgeInsets.only(bottom: 10.0)),
      ],
    );
  }
}

showComments(BuildContext context,
    {String postId, String ownerId, String mediaUrl}) {
  Navigator.push(context, MaterialPageRoute(builder: (context) {
    return Comments(
      postId: postId,
      postOwnerId: ownerId,
      postMediaUrl: mediaUrl,
    );
  }));
}

The argument type 'Context' error... Image here:

1 个答案:

答案 0 :(得分:0)

不能将参数类型Context分配给参数类型BuildContext

因此,您需要传递BuildContext而不是Context类型。尝试将构建上下文从小部件的build方法传递到buildPostFooter方法。

buildPostFooter(BuildContext context){
  ...

  GestureDetector(
    onTap: () => showComments(
      context,
      postId: postId,
      ownerId: ownerId,
      mediaUrl: mediaUrl,
   ),
   child: Icon(
       Icons.supervised_user_circle,
       size: 28.0,
       color: Colors.blueAccent,
     ),
   ),

   ...
}

然后在小部件的build方法中。我希望这能解决您的问题。

buildPostFooter(context),